package com.panda.business.task;


import com.panda.order.domain.TPandaOrderHead;
import com.panda.order.service.ITPandaOrderHeadService;
import com.panda.order.taobao.TbUpdateOrderFlgApi;
import com.panda.system.common.constant.EnumConstants;
import com.panda.system.domain.PandaTaskDetail;
import com.panda.system.service.IPandaTaskDetailService;
import com.panda.system.service.IPandaTaskService;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 同步管家婆订单
 */
@Component("updateOrderStatusTask")
@Transactional
public class UpdateOrderStatusTask {
    private static final Logger log = LoggerFactory.getLogger(UpdateOrderStatusTask.class);

    private static final List<String> BE_PAYMENT_STATUS = Arrays.asList("SELLER_CONSIGNED_PART","WAIT_SELLER_SEND_GOODS",
            "WAIT_BUYER_CONFIRM_GOODS","TRADE_BUYER_SIGNED","TRADE_FINISHED");
    @Autowired
    IPandaTaskDetailService taskDetailService;

    @Autowired
    IPandaTaskService taskService;

    @Autowired
    ITPandaOrderHeadService orderHeadService;

    @Autowired
    TbUpdateOrderFlgApi updateOrderFlgApi;


    public void updateOrderStatus(Date lastRun){
        // 查询未完成操作
        PandaTaskDetail detail =new PandaTaskDetail();
        detail.setStatus( EnumConstants.TaskDetailStatus.TO_PAY.getCode());
        List<PandaTaskDetail> pandaTaskDetails = taskDetailService.selectPandaTaskDetailList(detail);
        List<Date> taskDates = pandaTaskDetails.stream().map(PandaTaskDetail::getUpdateTime).collect(Collectors.toList());
        Date minDate = Collections.min(taskDates);
        log.info("判断订单成交状态，开始时间：{}",minDate);
        // 提高容错，开始时间前移一天
        Calendar cal = Calendar.getInstance();
        cal.setTime(minDate);
        cal.set(Calendar.DAY_OF_YEAR, -1);
        log.info("判断订单成交状态，容错时间：{}",cal.getTime());
        List<TPandaOrderHead> orderHeads = orderHeadService.queryTbOrderListByStartTime(cal.getTime());
        Map<String, List<TPandaOrderHead>> nickGroupOrderMap = orderHeads.stream().collect(Collectors.groupingBy(TPandaOrderHead::getBuyerNick));
        List<TPandaOrderHead> updateGjpOrderList = new ArrayList<>();
        for(PandaTaskDetail taskDetail:pandaTaskDetails){
            log.info("买家名称：{}",taskDetail.getBuyerNick());
            String key = taskDetail.getBuyerNick();
            if(Strings.isEmpty(key)){
                continue;
            }
            List<TPandaOrderHead> orderList = nickGroupOrderMap.get(key.trim());
            TPandaOrderHead orderHead = chickOperationOrder(orderList, taskDetail);
            // 已付款
            if(orderHead!=null&&Strings.isNotEmpty(orderHead.getTid())){
                updateGjpOrderList.add(orderHead);
                taskDetail.setStatus(EnumConstants.TaskDetailStatus.BE_PAY.getCode());
                taskDetail.setOrderNo(orderHead.getTid());
                taskDetail.setPaymentTime(orderHead.getPayTime());
                taskDetailService.updatePandaTaskDetail(taskDetail);

                // 创建返款任务
                taskDetailService.createitRebatesTask(taskDetail,taskDetail.getPandaTask().getPrice());

                // 创建评价任务
                if(EnumConstants.OrderType.EVALUTION.getCode().equals(taskDetail.getOrderType())){
                    taskDetailService.createEvaluationTodo(taskDetail);
                }
            }
        }
        updateOrderFlgApi.updateOrderFlg(updateGjpOrderList,4L);
    }

    private TPandaOrderHead chickOperationOrder(List<TPandaOrderHead> orderList,PandaTaskDetail taskDetail){
        if(CollectionUtils.isEmpty(orderList)){
            return null;
        }
        for(TPandaOrderHead orderHead:orderList){
            log.info("状态：{}，店铺ID：{}，{}",orderHead.getStatus(),orderHead.getStoreId(),taskDetail.getPandaTask().getStoreId());
            // 状态判断、店铺、
            if(BE_PAYMENT_STATUS.contains(orderHead.getStatus())
                    ){
                if(Long.valueOf(orderHead.getStoreId()).equals(taskDetail.getPandaTask().getStoreId())){
                    // 判断商品信息是否匹配
                    String url = taskDetail.getPandaTask().getUrl();
                    if(Strings.isNotEmpty(url)&& url.contains(orderHead.getNumIid())){
                        return orderHead;
                    }
                }


            }
        }
        return new TPandaOrderHead();
    }

    public static void main(String[] args) {

    }
}
